<template>
  <div class="h-screen flex justify-center items-center">
    <div class="flex flex-col">
      <div class="text-center">
        <span>登 录</span>
      </div>
      <div class="mt-4 w-96">
        <el-form ref="formRef" :model="formData" :rules="rules">

          <el-form-item prop="account">
            <el-input v-model="formData.account" placeholder="请输入账号" @keyup.enter="handleLogin">
              <template #prepend>
                <el-icon>
                  <User/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="formData.password" show-password placeholder="请输入密码" @keyup.enter="handleLogin">
              <template #prepend>
                <el-icon>
                  <Lock/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="flex flex-row-reverse">
          <el-checkbox v-model="isRemember" label="记住账号"></el-checkbox>
        </div>
        <el-button class="w-full" type="primary" @click="handleLogin">
          登 录
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import FormInstance from "element-plus";
import useUserStore from "@/stores/modules/user";
import {useRoute, useRouter} from "vue-router";
import {Lock, User} from "@element-plus/icons-vue";
import cache from "@/utils/cache";
import {CacheEnum} from "@/enums/cacheEnum";
import {PageEnum} from "@/enums/pageEnum";

const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const formRef = ref(FormInstance)
const isRemember = ref(false)
const formData = reactive({
  account: '',
  password: ''
})

const rules = {
  account: [
    {required: true, message: '请输入账号', trigger: ['blur']}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: ['blur']}
  ]
}

const handleLogin = async () => {

  cache.set(CacheEnum.ACCOUNT_KEY, {
    isRemember: isRemember.value,
    account: isRemember.value ? formData.account : ''
  })

  await formRef.value?.validate()
  await userStore.login(formData)
  const {
    query: {redirect}
  } = route
  const path = typeof redirect === 'string' ? redirect : PageEnum.INDEX
  await router.push(path)
}

onMounted(() => {
  const value = cache.get(CacheEnum.ACCOUNT_KEY)
  if (value?.isRemember) {
    isRemember.value = value.isRemember
    formData.account = value.account
  }
})
</script>

<style scoped>

</style>